package com.wangzhen.algorithm.Interview.ali;

import java.util.concurrent.Semaphore;

/**
 * @description: 启2个线程，使之交替打印1-100,如：两个线程分别为：Printer1和Printer2,
 *              最后输出结果为： Printer1 — 1 Printer2 一 2 Printer1 一 3 Printer2 一 4
 * @datetime: 2021/3/30   下午7:38
 * @author: 王震
 */
public class ThreadPrint2 {
    static int i=1;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore1 = new Semaphore(0);
        Semaphore semaphore2 = new Semaphore(0);
        Thread thread1 = new Thread(()->{
            while (i<=99){
                try {
                    semaphore1.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread1-"+i++);
                semaphore2.release();

            }
        });
        Thread thread2 = new Thread(()->{
            while (i<=100){
                try {
                    semaphore2.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2-"+i++);
                semaphore1.release();

            }
        });
        semaphore1.release();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();


    }
}
